package com.example.jsonquynh;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

public class BinderData extends BaseAdapter {
	List<Place> placeList;
	LayoutInflater inflater;
	Activity activity;

	public BinderData(Activity act, List<Place> placeList) {
		this.activity = act;
		this.placeList = placeList;
		inflater = (LayoutInflater) act
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		return placeList.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup viewGroup) {
		View rowView = convertView;
		if (rowView == null) {
			rowView = inflater.inflate(R.layout.list_row, null);
			ViewHolder holder = new ViewHolder();
			holder.tvTitle = (TextView) rowView.findViewById(R.id.tvTitle);
			holder.tvAddress = (TextView) rowView
					.findViewById(R.id.tvAddressDetail);
			holder.ivThumb = (ImageView) rowView.findViewById(R.id.list_image);
			rowView.setTag(holder);
		}
		ViewHolder holder = (ViewHolder) rowView.getTag();
		holder.tvTitle.setText(placeList.get(position).getTitle());
		holder.tvAddress.setText(placeList.get(position).getAddress());
		String img = placeList.get(position).getThumbnai();
		img = MainActivity.URL_SERVICE + "anh/thumbs/" + img;

		UrlImageViewHelper.setUrlDrawable(holder.ivThumb, img);
		return rowView;
	}

	public void loadThumb(final ImageView imgView, final String urlImg) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					URL url = new URL(urlImg);
					final Bitmap bmp = BitmapFactory.decodeStream(url
							.openConnection().getInputStream());
					activity.runOnUiThread(new Runnable() {

						@Override
						public void run() {
							imgView.setImageBitmap(bmp);

						}
					});

				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}).start();

	}

	static class ViewHolder {
		TextView tvTitle;
		TextView tvAddress;
		ImageView ivThumb;
	}
}
